#!/bin/bash

# 检查 socat 是否安装
if ! command -v socat &> /dev/null; then
    echo "Error: socat is not installed. Please install it first:"
    echo "sudo apt-get install socat"
    exit 1
fi

# 清理可能存在的旧进程
if [ -f /tmp/socat.pid ]; then
    echo "清理旧进程"
    kill $(cat /tmp/socat.pid) 2>/dev/null || true
    rm -f /tmp/socat.pid
fi

# 创建虚拟串口对
echo "创建虚拟串口对"
socat -d -d pty,raw,echo=0,link=/tmp/ttyVSP1 pty,raw,echo=0,link=/tmp/ttyVSP2 &
SOCAT_PID=$!

# 等待串口创建完成
sleep 1

# 检查串口是否创建成功
if [ ! -e "/tmp/ttyVSP1" ] || [ ! -e "/tmp/ttyVSP2" ]; then
    echo "Error: 创建虚拟串口失败"
    kill $SOCAT_PID
    exit 1
fi

echo "虚拟串口创建成功"
echo "Port 1: /tmp/ttyVSP1"
echo "Port 2: /tmp/ttyVSP2"
echo "Socat PID: $SOCAT_PID"

# 保存socat的PID以便后续清理
echo $SOCAT_PID > /tmp/socat.pid

# 设置串口权限
chmod 666 /tmp/ttyVSP1
chmod 666 /tmp/ttyVSP2

